import { observable } from 'mobx'
import Taro from '@tarojs/taro'

// 旅游目的地数据存储
const destinationsStore = observable({
  // 目的地列表

  destinations: [
    { id: 1, name: '巴黎', country: '法国', description: '浪漫之都', visited: false, latitude: 48.8566, longitude: 2.3522 },
    { id: 2, name: '东京', country: '日本', description: '现代与传统的融合', visited: false, latitude: 35.6762, longitude: 139.6503 },
    { id: 3, name: '纽约', country: '美国', description: '不夜城', visited: false, latitude: 40.7128, longitude: -74.0060 }
  ],
  
  // 添加新目的地
  addDestination(destination) {
    const newId = this.destinations.length > 0 
      ? Math.max(...this.destinations.map(d => d.id)) + 1 
      : 1;
    
    this.destinations.push({
      ...destination,
      id: newId,
      visited: false
    });
    
    return newId;
  },
  
  // 更新目的地信息
  updateDestination(id, updatedData) {
    const index = this.destinations.findIndex(dest => dest.id === id);
    if (index !== -1) {
      this.destinations[index] = {
        ...this.destinations[index],
        ...updatedData
      };
      return true;
    }
    return false;
  },
  
  // 删除目的地
  deleteDestination(id) {
    const index = this.destinations.findIndex(dest => dest.id === id);
    if (index !== -1) {
      this.destinations.splice(index, 1);
      return true;
    }
    return false;
  },
  
  // 标记目的地为已访问/未访问
  toggleVisited(id) {
    const destination = this.destinations.find(dest => dest.id === id);
    if (destination) {
      destination.visited = !destination.visited;
      // 保存更新后的数据到本地存储
      this.saveDestinations();
      return true;
    }
    return false;
  },
  
  // 从本地存储加载目的地数据
  loadDestinations() {
    try {
      const savedDestinations = Taro.getStorageSync('destinations');
      if (savedDestinations && savedDestinations.length > 0) {
        this.destinations.replace(savedDestinations);
      } else {
        // 如果本地存储中没有数据，保存当前默认数据
        this.saveDestinations();
      }
    } catch (error) {
      console.error('加载目的地数据失败:', error);
    }
  },
  
  // 保存目的地数据到本地存储
  saveDestinations() {
    try {
      Taro.setStorageSync('destinations', this.destinations.slice());
    } catch (error) {
      console.error('保存目的地数据失败:', error);
    }
  }
});

export default destinationsStore;